package cn.dansj.configure;

import cn.dansj.bean.InterfaceConstant;
import cn.dansj.enums.GlobalEnv;
import cn.dansj.common.request.RequestUtils;
import cn.dansj.common.utils.transfer.*;
import cn.dansj.utils.project.ProjectUtils;
import cn.dansj.utils.resolver.TokenResolver;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class RequestConfigure implements WebMvcConfigurer, HandlerInterceptor {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String method = request.getMethod();
        String controller = handler.getClass().equals(HandlerMethod.class) ? ((HandlerMethod) handler).getMethod().getDeclaringClass().getName() : null;
        //调用接口的请求不拦截,直接转发到接口控制器
        if (ProjectUtils.isApiPrefix()) {
            if (ArrayUtils.asList("POST", "GET").contains(method)) {
                RequestUtils.dispatcher(InterfaceConstant.InterfaceBaseRequestURI).apiRequest().start();
            } else {
                ProjectUtils.recordRequestLog(request, 404, "路由地址不存在", controller, true);
                RequestUtils.response404();
            }
            return false;
        }
        return true;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(this);
        //所有路径都被拦截
        registration.addPathPatterns("/**");
        //添加不拦截路径
        registration.excludePathPatterns(GlobalEnv.excludePathPatterns);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new TokenResolver());
    }
}
